<template>
  <div>
    <el-input v-model="searchinput"
              class="w-50 m-2"
              size="large"
              placeholder="输入搜索的文章"
              :suffix-icon="Search"
              style="width:250px;margin-left:50px" />
    <el-date-picker v-model="searchdate"
                    type="daterange"
                    range-separator="To"
                    start-placeholder="Start date"
                    end-placeholder="End date" />
    <el-table :data="essays"
              @expand-change="expandchange"
              style="width: 100%">
      <el-table-column type="expand">
        <template #default="oneessay">
          <el-table :data="comments"
                    style="width:70%;margin-left:200px">
            <el-table-column label="内容"
                             prop="content" />
            <el-table-column label="创建时间"
                             prop="createAt" />
            <el-table-column fixed="right"
                             label="Operations"
                             width="260">
              <template #default="scope">
                <el-popconfirm title="此操作会删除对应的文章,你确定吗？"
                               @confirm="handleDeletecomment(scope.row.id,oneessay.row)">
                  <template #reference>
                    <el-button size="small"
                               type="danger">删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="标题"
                       prop="title" />
      <el-table-column label="封面"
                       width="100">
        <template #default="props">
          <img :src="props.row.cover"
               width="40"
               height="40"
               alt="">
        </template>
      </el-table-column>
      <el-table-column label="内容"
                       prop="content"
                       style="height:40px" />
      <el-table-column label="发表日期"
                       width="180"
                       prop="createAt" />
      <el-table-column fixed="right"
                       label="Operations"
                       width="260">
        <template #default="scope">>
          <el-button size="small"
                     @click="checkcontent(scope.row.content)">查看文章内容</el-button>
          <el-popconfirm title="删除评论"
                         @confirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button size="small"
                         type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination background
                   style="width:200px;margin:10px auto"
                   layout="prev, pager, next"
                   :page-size="6"
                   v-model:current-page="start"
                   :total="total" />
  </div>
  <el-dialog v-model="dialogTableVisible"
             title="查看文章内容">
    <div class="content"
         style="overflow:auto;height:400px">
      <MdEditor previewOnly
                v-model="curessaycontent"></MdEditor>
    </div>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref, watch } from 'vue'
import { deleteessaybyidapi, mangetallessayapi } from '@/apis/essay'
import MdEditor from 'md-editor-v3'
import { debounce, formattime } from '@/utils'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { deletecomapi, mangetbyessayapi } from '@/apis/comment'
interface essayinter {
  id: number
  content: string
  cover: string
  title: string
  createAt: string
}
interface commentinter {
  id: number
  content: string
  createAt: string
}
export default defineComponent({
  name: 'v-essay',
  components: { MdEditor },
  setup() {
    const router = useRouter()
    const essays = ref<essayinter[]>() //文章
    const comments = ref<commentinter[]>() //评论
    const start = ref<number>(1) //分页查询
    const total = ref<number>(0) //文章总数
    const curessaycontent = ref<string>('') //当前查看的文章内容
    const dialogTableVisible = ref<boolean>(false)
    const searchinput = ref<string>('') //根据内容搜索文章
    const searchdate = ref<[string, string]>([
      formattime('0'),
      formattime(Date()),
    ]) //根据时间搜索
    //获取所有文章
    const mangetallessayfn = () => {
      mangetallessayapi(
        (start.value - 1) * 6,
        6,
        searchinput.value,
        formattime(searchdate.value ? searchdate.value[0] : '0'),
        formattime(searchdate.value ? searchdate.value[1] : Date())
      )
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        .then((res: any) => {
          const re = res.result.map((item: essayinter) => ({
            ...item,
            createAt: formattime(item.createAt),
          }))
          essays.value = re
          total.value = res.total
        })
        .catch(() => {
          ElMessage.error('身份失效')
          router.push('/login')
        })
    }
    //搜索
    watch(
      searchinput,
      debounce(() => {
        mangetallessayfn()
      })
    )
    watch(
      searchdate,
      debounce(() => {
        console.log(searchdate.value)

        mangetallessayfn()
      })
    )
    //分页改变
    watch(start, () => {
      mangetallessayfn()
    })
    onMounted(() => {
      mangetallessayfn()
    })

    //查看文章内容
    const checkcontent = (content: string) => {
      curessaycontent.value = content
      dialogTableVisible.value = true
    }
    //删除一个文章
    const handleDelete = async (id: number) => {
      try {
        await deleteessaybyidapi(id)
        ElMessage.success('删除成功')
        mangetallessayfn()
      } catch (e) {
        ElMessage.error('身份失效')
        router.push('/login')
      }
    }
    //展开行显示评论
    const expandchange = async (expandedRows: essayinter) => {
      try {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const re: any = await mangetbyessayapi(expandedRows.id)
        comments.value = re.result.map((item: commentinter) => ({
          ...item,
          createAt: formattime(item.createAt),
        }))
      } catch (e) {
        ElMessage.error('身份失效')
        router.push('/login')
      }
    }
    //删除评论
    const handleDeletecomment = async (
      commentid: number,
      curessay: essayinter
    ) => {
      try {
        await deletecomapi(commentid)
        ElMessage.success('删除评论成功')
        expandchange(curessay)
      } catch (e) {
        ElMessage.error('身份失效')
        router.push('/login')
      }
    }
    return {
      start,
      essays,
      total,
      checkcontent,
      curessaycontent,
      dialogTableVisible,
      handleDelete,
      searchinput,
      searchdate,
      expandchange,
      comments,
      handleDeletecomment,
    }
  },
})
</script>

<style scoped lang="less">
:deep(.cell) {
  height: 45px;
}
</style>